package com.ztjc.day02_storage.util;

import android.content.Context;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by pro on 15/10/7.
 */
public class InternalStorageUtil {

    /**
     * 保存账户信息
     *
     * @param context
     * @param account
     * @param pass
     * @return
     */
    public static boolean saveAccount(Context context, String account, String pass) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = context.openFileOutput("account.txt", Context.MODE_PRIVATE);
            fileOutputStream.write((account + "##" + pass).getBytes());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 获取账户信息
     *
     * @param context
     * @return
     */
    public static Map<String, String> getAccount(Context context) {
        Map<String, String> result = null;
        FileInputStream fileInputStream = null;
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;
        try {
            fileInputStream = context.openFileInput("account.txt");
            inputStreamReader = new InputStreamReader(fileInputStream);
            reader = new BufferedReader(inputStreamReader);
            String s = reader.readLine();
            String[] split = s.split("##");
            result = new HashMap<>();
            result.put("account", split[0]);
            result.put("pass", split[1]);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
